<?php
/**
 * @name ArticleController
 * @author xuebingwang
 * @desc 文章控制器
 * @see http://www.php.net/manual/en/class.yaf-controller-abstract.php
*/
class PaymentController extends MallController {

    public function init(){

        $this->config = Yaf\Registry::get('config');
        $this->wechat = new Wechat($this->config->wechat->toArray());

        SeasLog::setLogger('api/payment');
    }

    public function alipayAction($type='return'){

        $model = new Model('t_payment_setting');
        $payment = $model->get('*',['code'=>'alipay']);
        $pay_server = new \Payment\Alipay\Alipay($payment);
        $pay_server->afterPay($type != 'return');

        if($type == 'notify'){
            exit;
        }

        $model = new Model('t_orders');
        $where = [
            'sn'=>$pay_server->order['sn'],
            'pay_status'=>OrderModel::PAY_STATUS_PAYD
        ];
        $order = $model->get(['sn','status'],['AND'=>$where]);
        if(empty($order)){
            $this->error('订单尚未支付成功，如果您已经支付成功。请联系管理员');
        }elseif($order['status'] == OrderModel::STATUS_COMPLETED){
            //已完成的订单直接进入详情页面
            $this->redirect('/member/order/view/sn/'.$pay_server->order['sn'].'.html');
        }else{
            //待激活的订单进入激活页面
            $this->redirect('/member/order/activate/sn/'.$pay_server->order['sn'].'.html');
        }
    }

    public function wxpayAction($type='notify'){

        $model = new Model('t_payment_setting');
        $payment = $model->get('*',['code'=>'wxpay']);
        $payment['appid'] = $this->config->wechat->appid;
        $payment['appsecret'] = $this->config->wechat->appsecret;

        $pay_server = new \Payment\Wxpay\Wxpay($payment);
        $pay_server->afterPay($type != 'return');

        exit;
    }

    public function returnAction($sn=''){

        if(empty($sn)){
            $this->error('订单号不能为空!');
        }

        $model = new Model('t_orders');
        $where = [
            'sn'=>$sn,
            'pay_status'=>OrderModel::PAY_STATUS_PAYD
        ];
        $order = $model->get(['sn','status'],['AND'=>$where]);
        if(empty($order)){
            $this->error('订单尚未支付成功，如果您已经支付成功。请联系管理员');
        }else{
            //待激活的订单进入激活页面
            $this->redirect('/member/order/wait/sn/'.$sn.'.html');
        }

        $this->getView()->assign('order',$order);
    }
}
